/*
 * @Date         : 2024-05-11 17:15:40 星期6
 * @Author       : xut
 * @Description  :
 */
import { readFileSync } from "node:fs"
import grpc from "@grpc/grpc-js"
import helloProto from "./helloworld.proto.js"

// 读取证书和秘钥文件
const serverKey = readFileSync("server.key")
const serverCrt = readFileSync("server.crt")
// 定义服务器的 SSL 证书和键
const serverCredentials = grpc.ServerCredentials.createSsl(
  null,
  [
    {
      cert_chain: serverCrt,
      private_key: serverKey,
    },
  ],
  true
)

const GreeterServiceImpl = {
  sayHello: (call, cb) => {
    const response = { message: "Hello " + call.request.name }
    cb(null, response)
  },
}

const server = new grpc.Server()
server.addService(helloProto.Greeter.service, GreeterServiceImpl)
server.bindAsync(
  "0.0.0.0:50051",
  // grpc.ServerCredentials.createInsecure(),
  serverCredentials,
  (err, port) => {
    if (err !== null) {
      return console.error(err)
    }

    console.log("gRPC listening on 0.0.0.0:" + port)
  }
)
